<?php

namespace App\Jobs\Finance\Traits;

use App\Models\Department;
use App\Models\Finance\FinanceBranchBill;
use App\Models\Finance\FinanceBranchDetailBill;
use App\Models\ShopDetail;

trait FinanceBranchBillTrait
{
    public array $departGroupPrice=[];
    public array $shopGroupPrice=[];

    //创建分部账单
    public function createBranchBill($customerBill){
        $departments=[];
        if(count($customerBill->accountBills)){
            //账单按部门分组
            foreach ($customerBill->accountBills as $accountBill){
                $departments[$accountBill->shop->department_two_id][]=$accountBill;
            }
            //生成各个部门的账单
            foreach ($departments as $departmentId=>$accounts){
                $department=Department::find($departmentId);
                //部门总账单
                $branchData=$this->getBranchData($customerBill,$department,$accounts);
                $branchBill=FinanceBranchBill::create($branchData);
                $departConsult=0;
                $this->departGroupPrice=[];
                $this->shopGroupPrice=[];
                foreach ($accounts as $account){
                    //子帐单账单详情
                    $accountData=$this->getAccountData($branchBill,$account,$customerBill);
                    $departConsult+=$accountData['consult_quantity'];
                    $detailBill=FinanceBranchDetailBill::create($accountData);
                    //咨询量，价格按报价id分组
                    $this->setDepartGroupPrice($detailBill,$accountData);
                    //咨询量按店铺分组
                    $this->setShopGroupPrice($detailBill,$accountData);
                }
                //按报价分组算日均咨询，匹配价格
                $this->updateBranchConsult();
                //按店铺分组算店铺管理费
                $this->updateShopGroupTotal();
                //分部总账单
                $this->updateBranchBillData($branchBill,$departConsult);
            }
        }
    }
    //分部账单数据
    public function getBranchData($customerBill,$department,$accounts){
        return [
            'customer_bill_id'=>$customerBill->id,
            'department_id'=>$department->id,
            'department_name'=>$department->name,
            'bill_date'=>$customerBill->bill_date,
            'total_consult'=>$this->getTotalDepartmentConsult($accounts),
            'wx_group'=>$customerBill->settlement_group,
            'bill_period_start'=>$customerBill->bill_period_start,
            'bill_period_end'=>$customerBill->bill_period_end,
            'bill_type'=>$customerBill->bill_type,
            'bill_month'=>$customerBill->bill_month,
            'company_name'=>$customerBill->company_name,
            'customer_id'=>$customerBill->customer_id,
        ];
    }
    //咨询量，价格按报价id分组
    public function setDepartGroupPrice($detailBill,$accountData){
        $this->departGroupPrice[$accountData['department_quote_id']]['sub_bill_ids'][]=$detailBill->id;
        $this->departGroupPrice[$accountData['department_quote_id']]['sub_bill_consult'][]=$accountData['consult_quantity'];
        $this->departGroupPrice[$accountData['department_quote_id']]['service_price']=$accountData['service_price'];
        $this->departGroupPrice[$accountData['department_quote_id']]['group_start_end'][]=$this->getBranchServicePeriod($accountData['service_period']);
    }
    //咨询量，价格按报价id分组
    public function setShopGroupPrice($detailBill,$accountData){
        $this->shopGroupPrice[$accountData['shop_id']]['sub_bill_ids'][]=$detailBill->id;
        $this->shopGroupPrice[$accountData['shop_id']]['sub_bill_consult'][]=$accountData['consult_quantity'];
        $this->shopGroupPrice[$accountData['shop_id']]['service_price']=$accountData['service_price'];
        $this->shopGroupPrice[$accountData['shop_id']]['group_start_end'][]=$this->getBranchServicePeriod($accountData['service_period']);
    }

    //分部总咨询量
    public function getTotalDepartmentConsult($accounts){
        $total=0;
        foreach ($accounts as $a){
            $total+=$a->consult_quantity;
        }
        return $total;
    }
    //分部子账号账单数据
    public function getAccountData($branchBill,$account,$customerBill){
        $subAccount=$account->subAccount;
        $billEnd=$customerBill->bill_period_end;
        //账单期内是否切换过店铺
        $billStart=$this->getNewBillStart($subAccount,$customerBill->bill_period_start,$billEnd);
        $isNewStart=($billStart!=$customerBill->bill_period_start);
        if($isNewStart){
            $serviceStartEnd=$this->getServicePeriod($subAccount,$billStart,$billEnd);
            $consult=$this->getConsult($subAccount,$billStart,$billEnd);
            $overTimefee=$this->getOvertimeFee($subAccount,$billStart,$billEnd);
        }
        $departQuote=$this->getDepartmentQuote($account);
        return [
            'branch_bill_id'=>$branchBill->id,
            'sub_bill_id'=>$account->id,
            'shop_id'=>$account->shop_id,
            'shop_name'=>$account->shop_name,
            'sub_account_id'=>$account->sub_account_id,
            'sub_account'=>$account->sub_account,
            'service_period'=>$isNewStart?($serviceStartEnd['start'].'-'.$serviceStartEnd['end']):$account->service_period,
            'service_days'=>$isNewStart?$serviceStartEnd['service_days']:$account->service_days,
            'consult_column'=>$isNewStart?$consult['column']:$account->consult_column,
            'consult_quantity'=>$isNewStart?$consult['quantity']:$account->consult_quantity,
//            'shop_other_fee'=>$account->shop_other_fee,
            'overtime_fee'=>$isNewStart?($overTimefee->sum('price')):$account->branch_overtime_fee,
            'penalty_amount'=>$this->getPenalty('b_service_couplet',$account->sub_account_id, $billStart,$billEnd),
            'department_quote_id'=>$departQuote['department_quote_id'],
            'service_price'=>$departQuote['service_price'],
            'quotation_group_id'=>$account->quotation_group_id,
        ];
    }
    //子账号的店铺在账期内是否切换过
    public function getNewBillStart($subAccount,$billStart,$billEnd){
        if($subAccount->shop && $subAccount->shop->reassign_time){
            $reassignTime=$subAccount->shop->reassign_time;
            if(strtotime($reassignTime)>strtotime($billStart) && strtotime($reassignTime)<strtotime($billEnd)){
                return date('Y-m-d',strtotime($reassignTime));
            }
        }
        return $billStart;
    }
    //获取部门报价
    public function getDepartmentQuote($account){
        $departQuote=$account->shop->quotaionInfo->departmentQuote??null;
        return [
            'department_quote_id'=>$departQuote->id??'',
            'service_price'=>$departQuote->price_content??'',
        ];
    }

    //更新分部账单总量数据
    public function updateBranchBillData($branchBill,$departConsult){
        $data=[
            'total_consult'=>$departConsult,
        ];
        $branchBill->update($data);
    }
    //咨询量，日均咨询量，匹配报价
    public function updateBranchConsult(){
        foreach ($this->departGroupPrice as $departQuoteId=>$group){
            $quoteTotal=array_sum($group['sub_bill_consult']);
            $totalDays=$this->getConsultDays($group['group_start_end']);
            $dayAverage=$totalDays?round($quoteTotal/$totalDays,1):0;
            $price=$this->selectQuoteFinal($group['service_price'],$dayAverage);
            $data=[
                'quote_total_consult'=>$quoteTotal,
                'total_quote_consult_days'=>$totalDays,
                'quote_day_average_consult'=>$dayAverage,
                'service_quote_final'=>$price,
            ];
            FinanceBranchDetailBill::whereIn('id',$group['sub_bill_ids'])->update($data);
        }
    }
    //咨询量，日均咨询量，获取并更新店铺管理费
    public function updateShopGroupTotal(){
        foreach ($this->shopGroupPrice as $shopId=>$group){
            $shopDetail=ShopDetail::find($shopId);
            $quoteTotal=array_sum($group['sub_bill_consult']);
            $data=[
                'shop_other_fee'=>$this->getShopFee($shopDetail,$quoteTotal,$group['group_start_end']),
            ];
            FinanceBranchDetailBill::whereIn('id',$group['sub_bill_ids'])->update($data);
        }
    }

}
